define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            var admin_id = $("#table").attr("data-admin-id");
            var is_self = $("#table").attr("data-is-self");
            var is_open = $("#table").attr("data-is-open");

            if(is_self == '1'){
                if(is_open == '1'){
                    is_self_edit = true;//自评可编辑

                }else{
                    is_self_edit = false;//自评可编辑
                }
                
                is_first_edit = false;//上级可编辑
                is_true = false;//自评 不显示上级评分
            }else{
                if(is_open == '1'){
                    is_first_edit = true;//上级可编辑
                }else{
                    is_first_edit = false;//上级可编辑
                }
                is_self_edit = false;//自评不可编辑
                
                is_true = true; //显示上级评分
            }
          
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'performance/evaluation/index',
                    add_url: 'performance/evaluation/add',
                    edit_url: 'performance/evaluation/edit',
                    del_url: 'performance/evaluation/del',
                    multi_url: 'performance/evaluation/multi',
                    edit_per_url: 'performance/performance/edit',
                    table: 'evaluation',
                }
            });
            /**
             * 合并单元格
             * @param data  原始数据（在服务端完成排序）
             * @param fieldName 合并属性名称
             * @param colspan   合并列
             * @param target    目标表格对象
             */
            function mergeCells(data,fieldName,colspan,target){
                //声明一个map计算相同属性值在data对象出现的次数和
                var sortMap = {};
                for(var i = 0 ; i < data.length ; i++){
                    for(var prop in data[i]){
                        if(prop == fieldName){
                            var key = data[i][prop]
                            if(sortMap.hasOwnProperty(key)){
                                sortMap[key] = sortMap[key] * 1 + 1;
                            } else {
                                sortMap[key] = 1;
                            }
                            break;
                        } 
                    }
                }
                for(var prop in sortMap){
                    // console.log(prop,sortMap[prop])
                }
                var index = 0;
                for(var prop in sortMap){
                    var count = sortMap[prop] * 1;
                    $(target).bootstrapTable('mergeCells',{index:index, field:fieldName, colspan: colspan, rowspan: count});   
                    index += count;
                }
            }
            var table = $("#table");
            //更新表格
            $(document).on("click", ".btn-ref", function () {
                table.bootstrapTable('refresh', Table.api.init);
            });
           
            $(".ev-content").blur(function(){
                var content = $.trim($(".ev-content").val());

                if (content.length ==0){ 
                    
                    $("#error-alert").removeClass("hidden");
                   
                }
            });

            $(".ev-content").focus(function(){
                $("#error-alert").addClass("hidden");
            });
            $(document).on("click ","#save-content",function(){
                var content = $(".ev-content").val();
                var ids = $(".ev-content").attr("data-ids");
                if($.trim(content.length) == 0){
                    $("#error-alert").removeClass("hidden");
                    return;
                }
                var curRow = {};
                curRow['row[superior_content]'] = content;
                $.ajax({
                    type: 'POST',
                    url: $.fn.bootstrapTable.defaults.extend.edit_per_url+"/ids/"+ids,
                    data:curRow,
                    dataType: 'JSON',
                    success: function (data, textStatus, jqXHR) {
                        if(data.code =='1'){
                            alert("修改成功");
                            var url ="performance/admin";
                            var nowurl = "performance/evaluation";
                            Backend.api.closetabs(nowurl);
                            

                            //新菜单 跳转;不能使用window.location.href;内部跳转无用
                            Backend.api.addtabs(url);
                              
                        }else{
                            alert(data.msg);
                        }
                       
                    },
                    error: function () { alert("error");}
                });
            })
            
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                cache : 'false',
              
                queryParams:function (params) {
                    
                    //自定义参数 ，固定参数不做修改
                     return {  
                        limit:params.limit,
                        search:params.search,
                        filter:params.filter,  
                        offset:params.offset,  
                        order:params.order,  
                        sort:params.sort,
                       
                        
                    };
                },
               
                escape : false,
                pageSize : '20',
                editable:true,
                pagination: false,
                showToggle:false,//不需要切换卡片视图和表格视图两种模式
                showExport: false,//不需要导出功能
                // commonSearch: false,//不需要通用搜索功能
                search: false,//不需要搜索框功能 配合protected $relationSearch = "id,month,year";
                operate: false,//控制字段列不参考搜索
                showColumns: false,//可以快速切换字段列的显示和隐藏
                onEditableSave: function (field, row, oldValue, $el) {
             
                var curRow = {};
                
                curRow['row['+field+']'] = row[field];

                    $.ajax({
                        type: 'POST',
                        url: $.fn.bootstrapTable.defaults.extend.edit_url+"/ids/"+row.id,
                        data:curRow,
                        dataType: 'JSON',
                        success: function (data, textStatus, jqXHR) {
                            if(data.code =='1'){
                                // alert("修改成功");
                                table.bootstrapTable('refresh', Table.api.init);
                            }else{

                                alert(data.msg);
                            }
                           
                        },
                        error: function () { alert("error");
                    }
                    });
                },


                columns: [
                    [
                        {checkbox: true,class:"hidden"},
                        {field: 'id',title:"ID", operate: false,class:"hidden"},
                        {field: 'admin_id', title:'序号',class:"hidden"},
                        {field: 'year', title: __('Year'), class:"hidden"},
                        {field: 'month', title: __('Month'), class:"hidden"},

                        {field: 'term',  operate: false,title:"大项分解"},
                        {field: 'termcontent',  operate: false,title:"详情"},
                        {field: 'self_score',  operate: false,title: __('Self_score'),editable:{
                            type: 'select',
                            is_edit: is_self_edit,
                            inputclass:'co-red',
                            source: [
                                {value: 5, text: '5.0'},
                                {value: 4.5, text: '4.5'},
                                {value: 4.0, text: '4.0'},
                                {value: 3.5, text: '3.5'},
                                {value: 3.0, text: '3.0'},
                                {value: 2.5, text: '2.5'},
                                {value: 2.0, text: '2.0'},
                                {value: 1.5, text: '1.5'},
                                {value: 1.0, text: '1.0'},
                                {value: 0.5, text: '0.5'},
                                // {value: 0.0, text: '0.0'},
                                ],
                            
                        } },
                        {field: 'superior_score', operate: false,visible:is_true, title: __('Superior_score'), editable: {
                            type: 'select',
                            is_edit: is_first_edit,
                            inputclass:'co-red',
                            source: [
                                {value: 5, text: '5.0'},
                                {value: 4.5, text: '4.5'},
                                {value: 4.0, text: '4.0'},
                                {value: 3.5, text: '3.5'},
                                {value: 3.0, text: '3.0'},
                                {value: 2.5, text: '2.5'},
                                {value: 2.0, text: '2.0'},
                                {value: 1.5, text: '1.5'},
                                {value: 1.0, text: '1.0'},
                                {value: 0.5, text: '0.5'},
                                // {value: 0.0, text: '0.0'},
                                ],

                        } },
                        // {field: 'superior_score',visible:is_true,title: __('Superior_score'),
                        // formatter: function (value, row, index) {
                            
                        //         if(admin_id == row.admin_id){

                        //             return row.superior_score;
                        //         }else{
                        //             if(row.superior_score == '0'){
                        //                 return "<span  style=\"color:red;\" name=\"row[superior_score]\" data-type=\"select\" data-pk=\""+row.id+"\" data-title=\"上级评分\">" + value + "</span>";
                        //             }else{
                        //                 // return "<span> </span>";
                        //                 return "<span  name=\"row[superior_score]\" data-type=\"select\" data-pk=\""+row.id+"\" data-title=\"上级评分\">" + value + "</span>";
                        //             }
                                    
                        //         }
                                
                        //     }
                        // },
                        {field: 'ave_score',visible:is_true, title: __('Ave_score'), operate: false,},
                        // {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: function (value, row, index) {
                        //     return '<a href="'+ $.fn.bootstrapTable.defaults.extend.edit_url+"/ids/"+row["id"] + '" class="btn btn-xs  btn-editone" title=""><i class="fa fa-pencil"></i></a>';
                        // }}
                        
                        //系统自带的有删除和修改操作
                        // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                onClickRow: function (row, $element) {
                   
                },
                onLoadSuccess: function (data) {
                    // $(".btn-delone").css("display",'none');
                    var data = $('#table').bootstrapTable('getData', true);
                   
                    //合并单元格
                    // mergeCells(data, "maxterm", 1, $('#table'));
                   
                },

            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            //取消双击弹出表格
            table.off('dbl-click-row.bs.table');
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();

            
        },
        api: {

            
            bindevent: function () {
               
               // $("#ping-box").data("validator-options", {
               //      valid: function (form) {
               //          form.submit();
               //          return true;
               //      }
               //  });
                Form.api.bindevent($("form[role=form]"));
            }

        }

    };
    return Controller;
});